const mysql = require('mysql2/promise')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

// 数据库连接配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'music_app',
  port: 3306,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
}

// 创建数据库连接池
let pool = mysql.createPool(dbConfig)

// 初始化数据库连接
async function initDatabase() {
  try {
    // 测试连接
    const conn = await pool.getConnection()
    await conn.query('SELECT 1')
    conn.release()
    console.log('✅ 数据库连接成功')
  } catch (err) {
    console.error('❌ 数据库连接失败:', err)
    // 重试逻辑
    let retries = 3
    while (retries--) {
      try {
        pool = mysql.createPool(dbConfig)
        const conn = await pool.getConnection()
        await conn.query('SELECT 1')
        conn.release()
        console.log('✅ 数据库重连成功')
        break
      } catch (err) {
        console.error(`❌ 数据库重连失败 (剩余尝试次数: ${retries}):`, err)
        if (retries === 0) process.exit(1)
        await new Promise(resolve => setTimeout(resolve, 5000))
      }
    }
  }
}

// 调用初始化函数
initDatabase()

class UserController {
  // 用户注册
  async register(ctx) {
    try {
      console.log('注册请求收到，请求体:', ctx.request.body);
      const { username, password, nickname, email } = ctx.request.body
      
      // 验证必填字段
      if (!username || !password) {
        console.log('用户名或密码为空');
        ctx.status = 400
        ctx.body = { code: 400, message: '用户名和密码不能为空' }
        return
      }

      // 检查用户名是否已存在
      try {
        const [rows] = await pool.query('SELECT user_id FROM users WHERE username = ?', [username])
        if (Array.isArray(rows) && rows.length > 0) {
          ctx.status = 400
          ctx.body = { code: 400, message: '用户名已存在' }
          return
        }
      } catch (err) {
        console.error('检查用户名失败:', err)
        ctx.status = 500
        ctx.body = { code: 500, message: '注册失败' }
        return
      }

      // 密码加密
      let hashedPassword
      try {
        const salt = await bcrypt.genSalt(10)
        hashedPassword = await bcrypt.hash(password, salt)
      } catch (err) {
        console.error('密码加密失败:', err)
        ctx.status = 500
        ctx.body = { code: 500, message: '注册失败' }
        return
      }

      // 创建用户
      const [result] = await pool.query(
        'INSERT INTO users (username, password, nickname, email, status) VALUES (?, ?, ?, ?, 1)',
        [username, hashedPassword, nickname || null, email || null]
      )

      ctx.body = { 
        code: 200, 
        message: '注册成功',
        data: {
          userId: result.insertId
        }
      }
    } catch (err) {
      console.error('注册失败:', err)
      ctx.status = 500
      ctx.body = { code: 500, message: '注册失败' }
    }
  }

  // 用户登录
  async login(ctx) {
    try {
      console.log('登录请求收到，请求体:', ctx.request.body);
      const { username, password } = ctx.request.body
      
      // 验证必填字段
      if (!username || !password) {
        console.log('用户名或密码为空');
        ctx.status = 400
        ctx.body = { code: 400, message: '用户名和密码不能为空' }
        return
      }

      // 查询用户
      console.log('正在查询用户:', username)
      let rows
      try {
        [rows] = await pool.query('SELECT user_id, username, password, nickname, avatar, email, phone, status FROM users WHERE username = ?', [username])
        console.log('查询结果:', rows)
        if (!Array.isArray(rows) || rows.length === 0) {
          ctx.status = 400
          ctx.body = { code: 400, message: '用户名或密码错误' }
          return
        }
      } catch (err) {
        console.error('查询用户失败:', err)
        ctx.status = 500
        ctx.body = { code: 500, message: '服务器内部错误' }
        return
      }

      const user = rows[0]

      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password)
      if (!isPasswordValid) {
        ctx.status = 400
        ctx.body = { code: 400, message: '用户名或密码错误' }
        return
      }

      // 生成JWT token
      const token = jwt.sign(
        { userId: user.user_id, username: user.username },
        process.env.JWT_SECRET || 'default-secret-key-please-change',
        { expiresIn: '7d' }
      )

      // 返回用户信息(不包含密码)
      const { password: _, ...userInfo } = user

      ctx.body = {
        code: 200,
        message: '登录成功',
        data: {
          token,
          userInfo
        }
      }
    } catch (err) {
      console.error('登录失败:', err)
      ctx.status = 500
      ctx.body = { code: 500, message: '登录失败' }
    }
  }

  // 获取用户详情
  async getUserDetail(ctx) {
    try {
      // 从token中获取用户ID
      const token = ctx.headers.authorization?.split(' ')[1]
      if (!token) {
        ctx.status = 401
        ctx.body = { code: 401, message: '未授权' }
        return
      }

      const decoded = jwt.verify(token, 'your-secret-key') // 请替换为实际的密钥
      const userId = decoded.userId

      // 查询用户信息
      const [rows] = await pool.query('SELECT * FROM users WHERE user_id = ?', [userId])
      if (rows.length === 0) {
        ctx.status = 404
        ctx.body = { code: 404, message: '用户不存在' }
        return
      }

      // 返回用户信息(不包含密码)
      const { password, ...userInfo } = rows[0]

      ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
          userInfo
        }
      }
    } catch (err) {
      console.error('获取用户信息失败:', err)
      if (err.name === 'JsonWebTokenError') {
        ctx.status = 401
        ctx.body = { code: 401, message: '无效的token' }
      } else {
        ctx.status = 500
        ctx.body = { code: 500, message: '获取用户信息失败' }
      }
    }
  }
}

module.exports = new UserController()